package com.ruoyi.storeAdd.controller;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.agent.domain.SysAgent;
import com.ruoyi.agent.mapper.SysAgentMapper;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.store.domain.SysStore;
import com.ruoyi.store.mapper.SysStoreMapper;

import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.storeAdd.domain.SysExpendDetails;
import com.ruoyi.storeAdd.service.ISysExpendDetailsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 商户充值订单Controller
 *
 * @author ruoyi
 * @date 2024-06-21
 */
@RestController
@RequestMapping("/storeAdd/storeAdd")
public class SysExpendDetailsController extends BaseController
{
    @Autowired
    private ISysExpendDetailsService sysExpendDetailsService;

    @Autowired
    private SysAgentMapper agentMapper;
    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysStoreMapper sysStoreMapper;

    /**
     * 查询商户充值订单列表
     */
//    @Anonymous
    @PreAuthorize("@ss.hasPermi('storeAdd:storeAdd:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysExpendDetails sysExpendDetails,
                              @RequestParam(name = "params[beginCreateTime]", required = false) Date beginCreateTime,
                              @RequestParam(name = "params[endCreateTime]", required = false) Date endCreateTime)
    {

        Long deptId = SecurityUtils.getDeptId();

        sysExpendDetails.setDeptId(deptId);
        if (beginCreateTime!=null) {
            sysExpendDetails.setBeginCreateTime(beginCreateTime);
        }
       if (endCreateTime!=null) {
           sysExpendDetails.setEndCreateTime(endCreateTime);
       }

        SysDept sysDept = sysDeptService.selectDeptById(deptId);
        String type = sysDept.getType();
        List<SysExpendDetails> list=null;
        //数据隔离：如果为管理端查询,则查询自己名下所有商铺的记录，
        if (type.equals("0") || type.equals("1")) {
            //管理端 或者 代理商端
            sysExpendDetails.setDeptId(deptId);
            startPage();
          list = sysExpendDetailsService.selectSysExpendDetailsList(sysExpendDetails);


        }


        else if(type.equals("2")) {
            //根据deptId查询对应的storeId
            List<SysStore> sysStores = sysStoreMapper.selectSysStoreByDeptId(deptId);
            if (CollectionUtils.isEmpty(sysStores)) {
                throw new ServiceException("当前用户异常");
            }

            Long storeId = sysStores.get(0).getId();
            sysExpendDetails.setStoreId(storeId);
            startPage();
            list = sysExpendDetailsService.selectSysExpendDetailsList(sysExpendDetails);

        }
















        if (CollectionUtils.isEmpty(list)) {
            return getDataTable(list);
        }
        List<Long> agentIds = list.stream().map(SysExpendDetails::getAgentId).collect(Collectors.toList());
        List<SysAgent> agents= agentMapper.selectSysAgentByIds(agentIds);

        Map<Long, String> agentNames = agents.stream().collect(Collectors.toMap(SysAgent::getId, c -> c.getName()));

        List<Long> userIds = new ArrayList<>(list.stream().map(SysExpendDetails::getUserId).collect(Collectors.toSet()));

        List<SysUser> users = userMapper.selectByIds(userIds);
        Map<Long, String> userMap = users.stream().collect(Collectors.toMap(SysUser::getUserId, c -> c.getUserName()));



        for (SysExpendDetails agentAdd : list) {
            agentAdd.setUserName(userMap.get(agentAdd.getUserId()));


            if (agentAdd.getAgentId()==0) {
                agentAdd.setAgentName("——————");
            }
            else {
                agentAdd.setAgentName(agentNames.get(agentAdd.getAgentId()));
            }

        }

        return getDataTable(list);
    }

    /**
     * 导出商户充值订单列表
     */
    @PreAuthorize("@ss.hasPermi('storeAdd:storeAdd:export')")
    @Log(title = "商户充值订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,SysExpendDetails sysExpendDetails,
                       @RequestParam(name = "params[beginCreateTime]", required = false) Date beginCreateTime,
                       @RequestParam(name = "params[endCreateTime]", required = false) Date endCreateTime)
    {
        Long deptId = SecurityUtils.getDeptId();



        sysExpendDetails.setDeptId(deptId);
        if (beginCreateTime!=null) {
            sysExpendDetails.setBeginCreateTime(beginCreateTime);
        }
        if (endCreateTime!=null) {
            sysExpendDetails.setEndCreateTime(endCreateTime);
        }

        //数据隔离：如果为管理端查询则


//        List<SysExpendDetails> list = sysExpendDetailsService.selectSysExpendDetailsList(sysExpendDetails);
        List<SysExpendDetails> list = sysExpendDetailsService.selectSysExpendDetailsList(sysExpendDetails);

        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("数据为空");
        }
        List<Long> agentIds = list.stream().map(SysExpendDetails::getAgentId).collect(Collectors.toList());
        List<SysAgent> agents= agentMapper.selectSysAgentByIds(agentIds);

        Map<Long, String> agentNames = agents.stream().collect(Collectors.toMap(SysAgent::getId, c -> c.getName()));

        List<Long> userIds = new ArrayList<>(list.stream().map(SysExpendDetails::getUserId).collect(Collectors.toSet()));

        List<SysUser> users = userMapper.selectByIds(userIds);
        Map<Long, String> userMap = users.stream().collect(Collectors.toMap(SysUser::getUserId, c -> c.getUserName()));



        for (SysExpendDetails agentAdd : list) {
            agentAdd.setUserName(userMap.get(agentAdd.getUserId()));


            if (agentAdd.getAgentId()==0) {
                agentAdd.setAgentName("——————");
            }
            else {
                agentAdd.setAgentName(agentNames.get(agentAdd.getAgentId()));
            }

        }
        ExcelUtil<SysExpendDetails> util = new ExcelUtil<SysExpendDetails>(SysExpendDetails.class);
        util.exportExcel(response, list, "商户充值订单数据");
    }

    /**
     * 获取商户充值订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('storeAdd:storeAdd:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysExpendDetailsService.selectSysExpendDetailsById(id));
    }

    /**
     * 新增商户充值订单
     */
    @PreAuthorize("@ss.hasPermi('storeAdd:storeAdd:add')")
    @Log(title = "商户充值订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysExpendDetails sysExpendDetails)
    {
        return toAjax(sysExpendDetailsService.insertSysExpendDetails(sysExpendDetails));
    }

    /**
     * 修改商户充值订单
     */
    @PreAuthorize("@ss.hasPermi('storeAdd:storeAdd:edit')")
    @Log(title = "商户充值订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysExpendDetails sysExpendDetails)
    {
        return toAjax(sysExpendDetailsService.updateSysExpendDetails(sysExpendDetails));
    }

    /**
     * 删除商户充值订单
     */
    @PreAuthorize("@ss.hasPermi('storeAdd:storeAdd:remove')")
    @Log(title = "商户充值订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysExpendDetailsService.deleteSysExpendDetailsByIds(ids));
    }
//    @Anonymous
//    @GetMapping("/getStoreChargeOrder")
//    public AjaxResult getStoreChargeOrder(@RequestParam Date startTime,@RequestParam Date endTime) throws ParseException {
//
//        Map<String,List<StoreChargeOrder>> map = new HashMap<>();
//        Long deptId = SecurityUtils.getDeptId();
//        SysDept sysDept = sysDeptService.selectDeptById(deptId);
//        if (sysDept.getType().equals("0")){
//            List<StoreChargeOrder> list = sysExpendDetailsService.getStoreChargeOrder();
//            map.put("list",list);
//        }
//        if (sysDept.getType().equals("1")){
//            List<StoreChargeOrder> list = sysExpendDetailsService.getAgentStoreChargeOrder(startTime,endTime,100L);
//            map.put("list",list);
//        }
//        return AjaxResult.success(map);
//    }



}
